package com.xfcycle.zebrabikegp.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.tencent.bugly.crashreport.CrashReport;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.util.ActivitiesStackUtil;
import com.xfcycle.zebrabikegp.util.PermissionsCheckerUtil;

/**
 * 启动页面窗体 专门负责检测用户是否已经给该APP赋予危险权限
 * <p>
 * Created by xFcycle on 2017/5/27.
 */

public class LaunchPageActivity extends AppCompatActivity {

    private TextView tv_change_activity_timer;

    public static final String[] PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
    };

    //权限检测工具类
    private PermissionsCheckerUtil mPermissionsCheckerUtil;

    //权限请求被拒绝
    public static final int PERMISSIONS_DENIED = 1;

    //系统权限管理页面参数
    private static final int PERMISSION_REQUEST_CODE = 0;

    //方案
    private static final String PACKAGE_URL_SCHEME = "package";

    //是否需要系统权限检测
    private boolean isRequireCheck = true;

    //Handle通知定时器更改数据
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            tv_change_activity_timer.setText(msg.obj.toString());
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launch_page);

        initView();

        ActivitiesStackUtil.getInstance().push(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //需要检查权限，则检查
        if (isRequireCheck) {
            if (mPermissionsCheckerUtil.judgePermissionListDenied(PERMISSIONS)) {
                //请求权限
                requestPermissions(PERMISSIONS);
            } else {
                //全部权限都已获取
                allPermissionsGranted();
            }
        }

        if(!isRequireCheck){
            //当秒数走到0，跳转页面
            if("0s".equals(tv_change_activity_timer.getText().toString())) {
                //跳转页面
                Intent int_Change_Activity = new Intent();
                int_Change_Activity.setClassName(LaunchPageActivity.this, RootActivity.LOGIN_ACTIVITY);
                startActivity(int_Change_Activity);
            }
        }

        isRequireCheck = !isRequireCheck;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivitiesStackUtil.getInstance().pop();
    }

    /**
     * 初始化组件
     */
    private void initView() {
        mPermissionsCheckerUtil = new PermissionsCheckerUtil(this);

        tv_change_activity_timer = (TextView) findViewById(R.id.tv_change_activity_timer);

        //初始化Bugly异常检测
        CrashReport.initCrashReport(getApplicationContext(), "ed46de5708", true);
    }

    /**
     * 请求权限 兼容低版本
     *
     * @param permissions 权限列表
     */
    private void requestPermissions(String[] permissions) {
        ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
    }

    /**
     * 全部的请求权限都已获取
     */
    private void allPermissionsGranted() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //等待两秒
                int i = 2;
                do{
                    SystemClock.sleep(990);
                    i--;
                    Message msg = new Message();
                    msg.obj = i + "s";
                    handler.sendMessage(msg);
                }while (i>0);

                //跳转页面
                Intent int_Change_Activity = new Intent();
                int_Change_Activity.setClassName(LaunchPageActivity.this, RootActivity.LOGIN_ACTIVITY);
                startActivity(int_Change_Activity);
            }
        }).start();
    }

    /**
     * 用户权限处理
     * 如果所需权限已全部获取，则直接跳过
     * 若未全部获取，则跳出提示dialog
     * 每隔几秒系统会进行一次判断 注意
     *
     * @param requestCode  请求码
     * @param permissions  权限
     * @param grabtResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grabtResults) {

        if (requestCode == PERMISSION_REQUEST_CODE && hasAllPermissionsGranted(grabtResults)) {
            isRequireCheck = true;
            //所有权限都已获取
            allPermissionsGranted();
        } else {
            isRequireCheck = false;
            //展示未获取权限Dialog
            showMissingPermissionDialog();
        }
    }

    /**
     * 判断是否已拥有所有权限
     *
     * @param grantResults 申请权限结果集
     * @return 返回判断权限 true为已拥有所有权限 false为有部分权限未被授权
     */
    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示缺失权限提示
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Help");
        builder.setMessage("This application lacks pivotal permissions,you can grant through \"Settings\"--\"Apps\"--App Name--\"Permissions\"...");

        //退出设置权限，直接退出应用
        builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                setResult(PERMISSIONS_DENIED);
                finish();
            }
        });

        //用户自己设置权限
        builder.setPositiveButton("Set", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        //创建弹出框
        AlertDialog dialog = builder.create();
        //展示弹出框
        dialog.show();
    }

    /**
     * 跳转到设置应用权限的系统setting页面 针对原生系统
     */
    private void startAppSettings() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        intent.setData(Uri.fromParts(PACKAGE_URL_SCHEME, getPackageName(), null));
        startActivity(intent);
    }
}
